package com.hoku.account.controller;

import com.hoku.account.model.Account;
import com.hoku.account.model.User;
import com.hoku.account.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.security.Principal;

/**
 * @author ZHUFEIFEI
 */
@RestController
public class AccountController {

    @Autowired
    private IAccountService accountService;

    @PreAuthorize("#oauth2.hasScope('server')")
    @GetMapping(path = "/{name}")
    public Account getAccountByName(@PathVariable String name) {
        return this.accountService.findByName(name);
    }

    @GetMapping(path = "/principal")
    public Principal principal(Principal principal) {
        return principal;
    }

    @GetMapping(path = "/current")
    public Account getCurrentAccount(Principal principal) {
        return this.accountService.findByName(principal.getName());
    }

    @PutMapping(path = "/current")
    public void saveCurrentAccount(Principal principal, @Valid @RequestBody Account account) {
        this.accountService.saveChanges(principal.getName(), account);
    }

    /**
     * 调用时http://192.168.72.115:9300/account/，后面必须有/
     * @param user
     * @return
     */
    @PostMapping(path = "/")
    public Account createNewAccount(@Valid @RequestBody User user) {
        return this.accountService.create(user);
    }
}
